# -*- coding: utf-8 -*-
import json

from django.utils.encoding import smart_unicode
from django.views.decorators.http import require_GET, require_POST
from future.utils import raise_with_traceback

from api.treasure.handler import weighted_random, view_my_treasures
from common.cache import redis_cache
from common.treasure.db import get_treasure_type_for_id, award_daily_treasure
from common.treasure.model import (TREASURE_AMOUNT, TREASURE_AVERAGE_VALUE)
from common.utils.api import (token_required, check_params)
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError
from common.utils.tz import today_str


@require_GET
@response_wrapper
@token_required
def get_my_treasure_v3(request):
    """
    查看我的宝箱记录
    """
    try:
        page = int(request.GET.get('page', 0))
        size = int(request.GET.get('size', 0))
    except Exception as e:
        raise_with_traceback(ParamError(e))

    s_list = view_my_treasures(request.user_id, page, size)
    data = {
        'list': s_list,
        'page': page if page > 0 else 1,
        'size': len(s_list)
    }
    return data


@require_POST
@response_wrapper
@token_required
def open_treasure_v3(request):
    param_dct = json.loads(smart_unicode(request.body))
    check_params(param_dct, ['treasure_id'])
    treasure_id = param_dct['treasure_id']
    user_id = request.user_id

    # 查询宝箱等级，宝箱抽取算法
    treasure_type = get_treasure_type_for_id(user_id, treasure_id)
    # 算出宝箱金额
    treasure_amount = int(weighted_random(TREASURE_AMOUNT[treasure_type]))

    # 读取redis，金额/计数
    [amount_field, count_field] = redis_cache.get_treasure_stats(treasure_type)
    if count_field == 0:
        # 写入交易, 宝箱金额至用户馀额, 更新数据库Treasure.status/Treasure.amount
        award_daily_treasure(user_id, treasure_id, treasure_amount, today_str())
        # 把宝箱金额写入redis
        redis_cache.add_treasure_amount(treasure_type, treasure_amount)
    if count_field != 0:
        if int(amount_field) / float(count_field) > TREASURE_AVERAGE_VALUE[treasure_type]:
            # 如果大于平均值，返回最小宝箱，覆写金额
            treasure_amount = int(TREASURE_AMOUNT.get(treasure_type)[0][0])
            award_daily_treasure(user_id, treasure_id, treasure_amount, today_str())
            redis_cache.add_treasure_amount(treasure_type, treasure_amount)
        else:
            award_daily_treasure(user_id, treasure_id, treasure_amount, today_str())
            redis_cache.add_treasure_amount(treasure_type, treasure_amount)

    return {'treasure_amount': treasure_amount}


